struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};
 
class Solution {
public:
    int sumNumbers(TreeNode* root) {
        return sum(root, 0);
    }

    static int sum(TreeNode* node, int cur) {
        int ret = cur * 10 + node->val;
        if (node->left != nullptr && node->right != nullptr) {
            ret = sum(node->left, ret) + sum(node->right, ret);
        }
        else if (node->right != nullptr) {
            ret = sum(node->right, ret);
        }
        else if (node->left != nullptr) {
            ret = sum(node->left, ret);
        }
        return ret;
    }
};